package selef.xiafan.service.impl;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import selef.xiafan.dao.SysRoleDao;
import selef.xiafan.dao.SysUserRoleDao;
import selef.xiafan.dao.UserDao;
import selef.xiafan.dto.UserDTO;
import selef.xiafan.entity.system.SysRole;
import selef.xiafan.entity.user.SysUserRole;
import selef.xiafan.entity.user.User;
import selef.xiafan.query.UserQ;
import selef.xiafan.service.IUserService;
import selef.xiafan.util.result.PageResult;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class IUserServiceImpl implements IUserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private SysUserRoleDao sysUserRoleDao;
    @Autowired
    private SysRoleDao sysRoleDao;

    @Override
    public void add(User user) {
        userDao.save(user);
    }

    @Override
    public User getByUsername(String username) {
        return userDao.findByUsername(username);
    }

    @Override
    public int register(User user) throws ParseException {
        String username = user.getUsername();
        String realName = user.getRealName();
        String phone = user.getPhone();
        String email = user.getEmail();
        String password = user.getPassword();
        String createBy = user.getCreateBy();
        Date simpDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));


        user.setUsername(username);
        user.setRealName(realName);
        user.setPhone(phone);
        user.setEmail(email);
        user.setCreateTime(simpDate);
        user.setEnable(true);
        user.setCreateBy(createBy);
        user.setIsSys(true);

        if (username.equals("") || password.equals("")) {
            return 0;
        }

        boolean exist = isExist(username);
        if (exist) {
            return 2;
        }

        // 默认生成16位盐 先生成随机byte数组，再转成字符串类型的base64并返回
        String salt = new SecureRandomNumberGenerator().nextBytes().toString();
        int times = 2;
        // 对密码加密
        String encodedPassword = new SimpleHash("md5", password, salt, times).toString();
        user.setSalt(salt);
        user.setPassword(encodedPassword);

        userDao.save(user);
        return 1;
    }

    @Override
    public PageResult<User> findAll(UserQ userQ) {
        Integer page = (userQ.getPage() - 1) * userQ.getSize();
        Integer size = userQ.getSize();
        String username = userQ.getUsername();

        Long total = userDao.countAll();

        if(total==0L){
            return new PageResult<>();
        }
        if (username != "") {
            List<User> allByQuery = userDao.findAllByQuery(page, size, username); // 根据输入信息模糊查询，并判断是否是后台系统人员
            return new PageResult<User>(total, allByQuery);
        }
        List<User> allNoQuery = userDao.findAllNoQuery(page, size);
        return new PageResult<User>(total,allNoQuery);
    }

    @Override
    public List<String> isAdmin(Integer id) {
        List<String> nameList = new ArrayList<>();

        // 先查询用户id对应的角色id
        List<SysUserRole> sysUserRoles = sysUserRoleDao.findAllByUid(id);
        for (SysUserRole sysUserRole : sysUserRoles) {
            int rid = sysUserRole.getRid();
            // 将每一个角色id查询对应的角色装到集合中
            SysRole sysRoles = sysRoleDao.findById(rid);
            String name = sysRoles.getName();
            nameList.add(name);
        }
        return nameList;
    }

    /*
     * 更改用户启用状态
     * */
    @Override
    public Boolean changeEnable(Integer userId) {
        User userInDb = userDao.findById(userId);
        if (userInDb.getEnable()) {
            userInDb.setEnable(false);
            userDao.save(userInDb);
            return true;
        } else if (!userInDb.getEnable()) {
            userInDb.setEnable(true);
            userDao.save(userInDb);
            return true;
        }

        return false;
    }

    @Override
    @Transactional
    public void delete(User user) {
        User userInQuery = userDao.findByUsername(user.getUsername());
        List<Integer> id = sysUserRoleDao.findAllByUid(user.getId())
                .stream().map(SysUserRole::getId).collect(Collectors.toList());
        if (userInQuery.getUsername().equals(user.getUsername()) || userInQuery.getId().equals(user.getId()) || userInQuery.getGender().equals(user.getGender())) {
            Iterator<Integer> next = id.iterator();
            while (next.hasNext()) {
                sysUserRoleDao.deleteById(next.next());
            }
            userDao.deleteByUsername(user.getUsername());
        }
    }

    @Override
    public boolean isExist(String username) {
        User user = userDao.findByUsername(username);
        return null != user;
    }

    @Override
    @Transactional
    public void edit(UserDTO editUserDTO) {
        User user = editUserDTO.getUser();
        List<Integer> roles = editUserDTO.getRoles();

        sysUserRoleDao.deleteAllByUid(user.getId());

        Iterator<Integer> iterator = roles.iterator();
        while (iterator.hasNext()) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRid(iterator.next());
            sysUserRole.setUid(user.getId());
            sysUserRoleDao.save(sysUserRole);
        }

        userDao.save(user);
    }

    @Override
    public void restPassword(User user) {
        String username = user.getUsername();
        User userInDb = userDao.findByUsername(username);
        String pinyin = getPinyin(username);
        String salt = new SecureRandomNumberGenerator().nextBytes().toString();
        int times = 2;
        // 对密码加密
        String encodedPassword = new SimpleHash("md5", pinyin, salt, times).toString();
        userInDb.setSalt(salt);
        userInDb.setPassword(encodedPassword);
        userDao.save(userInDb);
    }

    @Override
    @Transactional
    public void batchDelete(List<User> user) {
        Iterator<User> iterator = user.iterator();
        while (iterator.hasNext()){
            userDao.deleteById(iterator.next().getId());
        }
    }

    public static String getPinyin(String text) {
        char[] chars = text.toCharArray();
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        // 设置大小写
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        // 设置声调表示方法
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        // 设置字母u表示方法
        format.setVCharType(HanyuPinyinVCharType.WITH_V);
        String[] s;
        String rs = StringUtils.EMPTY;
        try {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < chars.length; i++) {
                // 判断是否为汉字字符
                if (String.valueOf(chars[i]).matches("[\\u4E00-\\u9FA5]+")) {
                    s = PinyinHelper.toHanyuPinyinStringArray(chars[i], format);
                    if (s != null) {
                        sb.append(s[0]);
                        continue;
                    }
                }
                sb.append(String.valueOf(chars[i]));
            }
            rs = sb.substring(0, sb.length());
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
        }
        return rs;
    }

    public static void main(String[] args) {
        /*String salt = new SecureRandomNumberGenerator().nextBytes().toString();
        int times = 2;
        String password = "123";
        // 对密码加密
        String encodedPassword = new SimpleHash("md5", password, salt, times).toString();
        System.out.println(salt);
        System.out.println(encodedPassword);*/

//        String username = "里斯li";
//        System.out.println(getPinyin(username));

    }

}
